package com.example.cloudgateway.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 记录当前ip访问的次数
 */
@Component
@Slf4j
public class IPAddressStatisticsFilter implements GlobalFilter, Ordered {

    public static final Map<String, AtomicInteger> CACHE = new ConcurrentHashMap<>();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取客户端的ip地址
        InetSocketAddress host = exchange.getRequest().getHeaders().getHost();
        //如果获取不到 返回 400 错误
        if (host == null || host.getHostName() == null) {
            exchange.getResponse().setStatusCode(HttpStatus.BAD_REQUEST);
            return exchange.getResponse().setComplete();
        }
        //否则的话 记录当前ip访问次数
        String hostName = host.getHostName();
        AtomicInteger count = CACHE.getOrDefault(hostName, new AtomicInteger(0));
        count.incrementAndGet();
        CACHE.put(hostName, count);
        log.info("IP地址：" + hostName + ",访问次数：" + count.intValue());
        return chain.filter(exchange);

    }

    /**
     * order的值越小,当前过滤器加载的顺序 就越先被执行
     * 越小越靠前  越大越靠后
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -1;
    }
}
